package mapro

import (
	"log"
	"server/lib/mysqldb"
	// "server/lib/redis"
	"encoding/json"
	// "reflect"
	"fmt"
	"strconv"
	"strings"
	"time"
)

func Update_product(str string) []string {
	goods_query_sql := "SELECT id FROM xx_goods WHERE sn = ?"
	// product_query_sql := "SELECT id, price, specification_values, stock, goods FROM xx_product WHERE goods = ?"
	goods_update_sql := "UPDATE xx_goods SET specification_items = ?, mincart = ? WHERE id = ?"
	product_del_sql := "DELETE FROM xx_product WHERE goods = ?"

	now := time.Now().Format("2006-01-02 15:04:05")
	ret := make([]string, 0)

	db := mysqldb.GetConnect()
	stran, err := db.IBagin()

	if err == nil {
		// 换行转数组
		strs := strings.Split(str, "\r\n")
		for i, j := range strs {
			// log.Println(i, j)
			if i%1000 == 0 {
				stran.Commit()
				stran, _ = db.IBagin()
			}
			if i > 0 && j != "" {
				// 逗号分隔数组
				stmp := strings.Split(j, ",")
				// 查询型号对应 的商品
				goods, _ := stran.IExecute(goods_query_sql, stmp[0])

				if len(goods) > 0 {
					// 查询商品规格
					// product, _ := stran.IExecute(product_query_sql, goods[0]["id"])
					count := 0
					gsave := make([]map[string]interface{}, 0)
					gw := make([]map[string]interface{}, 0)
					gsave = append(gsave, map[string]interface{}{
						"name": "货期",
					})
					gsave = append(gsave, map[string]interface{}{
						"name": "数量",
					})
					// 删除商品规格
					stran.IDel(product_del_sql, goods[0]["id"])
					// 循环插入规格
					for x, y := range stmp[7:26] {
						if x%2 == 1 && stmp[7:][x-1] != "" && y != "" && stmp[7:][x-1] != "0" && y != "0" {
							var m []map[string]interface{}
							mstmp := make(map[string]interface{})
							mstmp["id"] = count + 2
							mstmp["value"] = stmp[7:][x-1]
							m = append(m, map[string]interface{}{"id": 0, "value": "境内7天"})
							m = append(m, mstmp)
							js, _ := json.Marshal(m)
							insert := map[string]interface{}{}
							insert["create_date"] = now
							insert["modify_date"] = now
							insert["version"] = 0
							insert["allocated_stock"] = 0
							insert["exchange_point"] = 0
							if count == 0 {
								insert["is_default"] = 1
							} else {
								insert["is_default"] = 0
							}
							insert["market_price"] = y
							insert["price"] = y
							insert["reward_point"] = count
							insert["sn"] = stmp[0] + "_" + strconv.Itoa(count)
							insert["specification_values"] = string(js)
							insert["stock"] = stmp[5]
							insert["goods"] = goods[0]["id"]

							_, err = stran.IInsertmanay("xx_product", insert)
							gw = append(gw, map[string]interface{}{
								"id":         count + 2,
								"value":      stmp[7:][x-1],
								"isSelected": true,
							})
							if err != nil {
								log.Println(err)
							}

							count = count + 1
						}
					}

					gs := make([]map[string]interface{}, 0)
					gs = append(gs, map[string]interface{}{
						"id":         0,
						"value":      "境内7天",
						"isSelected": true,
					})

					//境外14天
					// kcount := count
					// 循环插入规格
					for x, y := range stmp[29:48] {
						if x%2 == 1 && stmp[7:][x-1] != "" && y != "" && stmp[7:][x-1] != "0" && y != "0" {
							bstmp := true
							bcount := count + 2
							for _, cs := range gw {
								if cs["value"] == stmp[29:][x-1] {
									bstmp = false
									bcount = cs["id"].(int)
									break
								}
							}
							var m []map[string]interface{}
							mstmp := make(map[string]interface{})
							mstmp["id"] = bcount
							mstmp["value"] = stmp[7:][x-1]
							m = append(m, map[string]interface{}{"id": 1, "value": "境外14天"})
							m = append(m, mstmp)
							js, _ := json.Marshal(m)
							insert := map[string]interface{}{}
							insert["create_date"] = now
							insert["modify_date"] = now
							insert["version"] = 0
							insert["allocated_stock"] = 0
							insert["exchange_point"] = 0
							insert["is_default"] = 0
							insert["market_price"] = y
							insert["price"] = y
							insert["reward_point"] = count
							insert["sn"] = stmp[0] + "_" + strconv.Itoa(count)
							insert["specification_values"] = string(js)
							insert["stock"] = stmp[5]
							insert["goods"] = goods[0]["id"]

							_, err = stran.IInsertmanay("xx_product", insert)
							if bstmp {
								gw = append(gw, map[string]interface{}{
									"id":         count + 2,
									"value":      stmp[29:][x-1],
									"isSelected": true,
								})
							}
							if err != nil {
								log.Println(err)
							}

							count = count + 1
						}
					}

					gs = append(gs, map[string]interface{}{
						"id":         1,
						"value":      "境外14天",
						"isSelected": true,
					})
					gsave[1]["entries"] = gw
					gsave[0]["entries"] = gs

					jmg, _ := json.Marshal(gsave)
					log.Println(string(jmg))
					// 更新产品的规格（货期，数量）
					_, err = stran.IUpdate(goods_update_sql, string(jmg), stmp[4], goods[0]["id"])
					if err != nil {
						ret = append(ret, stmp[0])
					}
				} else {
					ret = append(ret, stmp[0])
				}
			}
		}
	} else {
		log.Println(err)
	}
	stran.Commit()
	return ret
}

func Select_product(str string) string {
	sql := "SELECT id, specification_values, stock FROM xx_product WHERE goods = ?"
	update_sql := "UPDATE xx_product SET stock = ? WHERE id in [%s]"

	db := mysqldb.GetConnect()
	tran, _ := db.IBagin()
	ids, _ := tran.IExecute(sql, str)

	minstock := -1
	mid := make([]string, 0)
	mb := false
	iminstock := -1
	imid := make([]string, 0)
	imb := false
	// updateId := make([]string{})
	for _, j := range ids {
		stock, _ := strconv.Atoi(j["stock"])
		var v []map[string]interface{}
		json.Unmarshal([]byte(j["specification_values"]), &v)
		if len(v) > 0 {
			if v[0]["value"] == "境内7天" {
				mid = append(mid, j["id"])
				if stock <= minstock {
					minstock = stock
					if mb {
						mb = true
					}

				} else if minstock == -1 {
					minstock = stock
				}
			} else if v[0]["value"] == "境外14天" {
				imid = append(imid, j["id"])
				if stock <= iminstock {
					iminstock = stock
					if imb {
						imb = true
					}
				} else if iminstock == -1 {
					iminstock = stock
				}
			}
		}
	}

	if minstock != -1 && mb {
		tran.IUpdate(fmt.Sprintf(update_sql, strings.Join(mid, ",")), minstock)
	}
	if iminstock != -1 && imb {
		tran.IUpdate(fmt.Sprintf(update_sql, strings.Join(mid, ",")), iminstock)
	}
	tran.Commit()
	// log.Println(minstock, iminstock)
	// log.Println(mid, imid)

	if minstock == -1 && len(ids) > 0 {
		return ids[0]["stock"]
	} else if len(ids) > 0 {
		return strconv.Itoa(minstock)
	}
	return "0"
}
